package org.moda.common;

import java.util.Optional;
import java.util.function.BiFunction;

public class ArrayUtil {
    public static <T> Optional<Tuple2<Integer, T>> index(T[] arr, T source, BiFunction<T, T, Boolean> f) {
        if (null == arr || 0 == arr.length) {
            return Optional.empty();
        }

        BiFunction<T, T, Boolean> fx = (t1, t2) -> Try.of(() -> f.apply(t1, t2)).toOptional().orElse(false);
        for (int i = 0; i < arr.length; i++) {
            if (fx.apply(arr[i], source)) {
                return Optional.of(Tuple2.of(i, arr[i]));
            }
        }
        return Optional.empty();
    }
}
